﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// Simple Service Administration Tool for WinNT based systems.
// Copyright © 2010 - Silvan Gehrig
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// 
// Author:
//  Silvan Gehrig
//
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.ComponentModel;
using SSATool.BL.DM;
using SSATool.Common.Util;
using SSATool.Common.Util.WeakEvents;

#endregion

namespace SSATool.UI.ViewModel
{
    /// <summary>
    /// Represents a service instance.
    /// </summary>
    public class DataService : INotifyPropertyChanged
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private readonly DataServiceCollection _parent;
        private readonly Service _service;

        private bool _eventAdded = false;
        private PropertyChangedEventHandler _onPropertyChanged;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets a value indicating whether the service can be paused and resumed.
        /// </summary>
        /// <returns>
        /// Returns true if the service can be paused; otherwise, false.
        /// </returns>
        public bool CanPauseAndContinue
        {
            get { return _service.CanPauseAndContinue; }
        }

        /// <summary>
        /// Gets a value indicating whether the service should be notified when the system
        /// is shutting down.
        /// </summary>
        /// <returns>
        /// Returns true if the service should be notified when the system is shutting down;
        /// otherwise, false.
        /// </returns>
        public bool CanShutdown
        {
            get { return _service.CanShutdown; }
        }

        /// <summary>
        /// Gets a value indicating whether the service can be stopped after it has started.
        /// </summary>
        /// <returns>
        /// Returns true if the service can be stopped; otherwise, false.
        /// </returns>
        public bool CanStop
        {
            get { return _service.CanStop; }
        }

        /// <summary>
        /// Gets or sets a friendly name for the service.
        /// </summary>
        public string DisplayName
        {
            get { return _service.DisplayName; }
        }

        /// <summary>
        /// Gets or sets the name of the computer on which this service resides.
        /// </summary>
        public string MachineName
        {
            get { return _service.MachineName; }
        }

        /// <summary>
        /// Gets or sets the name that uniquely identifies the service that this instance references.
        /// </summary>
        public string ServiceName
        {
            get { return _service.ServiceName ?? string.Empty; }
        }

        /// <summary>
        /// Gets/sets the status of the service that is referenced by this instance.
        /// </summary>
        public DataServiceStatus Status
        {
            get { return (DataServiceStatus)Enum.ToObject(typeof(DataServiceStatus), (short)_service.Status); }
        }

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------
        
        /// <summary>
        /// Initializes a new instance of the <see cref="DataService"/> class.
        /// </summary>
        internal DataService(DataServiceCollection parent, Service service)
        {
            PreCondition.AssertNotNull(parent, "parent");
            PreCondition.AssertNotNull(service, "service");
            _service = service;
            _parent = parent;
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------


        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="left">Specifies the left object.</param>
        /// <param name="right">Specifies the right object.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(DataService left, DataService right)
        {
            // If both are null, or both are same instance, return true.
            if (ReferenceEquals(left, right))
            {
                return true;
            }

            // If one is null, but not both, return false.
            if ((object)left == null || (object)right == null)
            {
                return false;
            }

            // Return true if the fields match:
            return left.Equals(right);
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="left">Specifies the left object.</param>
        /// <param name="right">Specifies the right object.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(DataService left, DataService right)
        {
            return !(left == right);
        }

        /// <summary>
        /// Determines whether the specified IDataObject is equal to the current object.
        /// </summary>
        /// <param name="toCompare">Parameter to check.</param>
        /// <returns>Returns true if the objects are equal.</returns>
        public override bool Equals(object toCompare)
        {
            // If parameter cannot be cast to DomainBase return false.
            return Equals(toCompare as DataService);
        }

        /// <summary>
        /// Determines whether the specified IDataObject is equal to the current object.
        /// </summary>
        /// <param name="obj">Parameter to check.</param>
        /// <returns>Returns true if the objects are equal.</returns>
        public bool Equals(DataService obj)
        {
            // If parameter is null return false:
            if ((object)obj == null) // force compiler to use Object::operator==()
                return false;

            // Return true if the fields match:
            return (obj.ServiceName == ServiceName);
        }

        /// <summary>
        /// Returns the hash code for this IDataObject.
        /// </summary>
        /// <returns>Returns the computed hash value.</returns>
        public override int GetHashCode()
        {
            return ServiceName.GetHashCode();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return string.Format("{0} [{1}]", base.ToString(), ServiceName);
        }

        /// <summary>
        /// Starts the current service.
        /// </summary>
        public void Start()
        {
            _service.Start();
        }

        /// <summary>
        /// Stops the current service.
        /// </summary>
        public void Stop()
        {
            _service.Stop();
        }

        /// <summary>
        /// Pauses the current service.
        /// </summary>
        public void Pause()
        {
            _service.Pause();
        }

        /// <summary>
        /// Continues the current service.
        /// </summary>
        public void Continue()
        {
            _service.Continue();
        }

        private void EnsureEventAdded()
        {
            if (!_eventAdded)
            {
                _service.PropertyChanged += OnPropertyChanged;
                _eventAdded = true;
            }
        }

        private void EnsureEventRemoved()
        {
            if (_onPropertyChanged != null && _eventAdded)
            {
                _service.PropertyChanged -= OnPropertyChanged;
                _eventAdded = false;
            }
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------
        
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged
        {
            add
            {
                _onPropertyChanged += value;
                EnsureEventAdded();
            }
            remove
            {
                _onPropertyChanged -= value;
                EnsureEventRemoved();
            }
        }

        /// <summary>
        /// Fires the PropertyChanged event.
        /// </summary>
        /// <param name="args">Event args to pass to the receivers.</param>
        protected void OnPropertyChanged(PropertyChangedEventArgs args)
        {
            _parent.FireChildChanged(this, args);

            if (_onPropertyChanged != null)
                _onPropertyChanged(this, args);
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            OnPropertyChanged(e);
        }

        #endregion
    }
}
